import util from "../../../../utils/util";
const app = getApp();
var QQMapWX = require('../../../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
    key: 'KR7BZ-XSQ3P-VGFD7-LNRZL-E7PXE-STF76'
});
var allInfo = [];
var leaveCityData = {};
Page({
    data: {
        citycode: "sz",
        city: '深圳',
        province: '广东',
        pindex: 0,
        cindex: 0,
        cityPick: ["选择城市"],
        showNav: true, // 快捷导航是否展开
        showShare: true, // 显示分享按钮
        leaveProvPick: [],
        leaveCityPick: [],
        leaveQu: ["请选择区县名称"],
        arriveQu: ["请选择区县名称"],
        provPick: [],
        leaveQuIndex: 0,
        arriveQuIndex: 0,
        leavePindex: 0,
        leaveCindex: 0,
        showMore: true,
        showDetail: false,
        detailInfo: "",
        leave: {
            "较低风险": "low",
            "低风险": "low",
            "中风险": "middle",
            "部分地区中风险": "middle",
            "高风险": "height",
            "较高风险": "height"
        },
        showMessage: [false, false, false, false, false, false],
        showDengji: [false, false, false, false],
        showAnnounce: false, //是否显示公告
        announce: '', //公告详情
        announceInfo: '', //公告地址
        toolArr: [], //工具箱
        subscribeText1: "+订阅城市",
        subscribeText2: "+订阅城市",
        showModalStatus: false,
        multiArray: [],
        multiIndex: [0, 0, 0],
        multiArray2: [],
        multiIndex2: [0, 0, 0],
        query1: [],
        query2: [],
        provinceArr: [],
        cityArr: [],
        quArr: [],
        fromCity: '深圳',
        fromCityCode: 'sz',
        fromQu: "全部",
        goCity: '请选择',
        goCityCode: '',
        goQu: "全部",
        differentTitle: [], //异地出行title数组
        differentContent: {}, //异地出行内容
        curDiffIndex: 0,
        curDiffTitle: '',
    },


    // 当出发地确认时
    async fromPickerChange(e) {
        if (this.data.multiArray[1][this.data.multiIndex[1]] == this.data.goCity) {
            ks.showToast({
                title: '请不要选择相同的城市',
                icon: 'none'
            })
            return
        }
        this.setData({
            multiIndex: e.detail.value,
            fromCity: this.data.multiArray[1][this.data.multiIndex[1]],
            fromCityCode: await this.getCityCode(this.data.multiArray[1][this.data.multiIndex[1]]),
            fromQu: this.data.multiArray[2][this.data.multiIndex[2]],
        })

        this.getDetailInfoData()

    },
    // 当出发地列发生变化时
    fromColumnChange: function (e) {
        var data = {
            multiArray: this.data.multiArray,
            multiIndex: this.data.multiIndex
        };
        data.multiIndex[e.detail.column] = e.detail.value;
        switch (e.detail.column) {
            case 0:
                let cityArr = this.data.query1.filter((item) => {
                    return item.province == this.data.multiArray[0][e.detail.value]
                })[0].citylist.map((item) => {
                    return item.cityname
                }).filter((item) => {
                    return item != "选择城市"
                })
                data.multiArray[1] = cityArr
                let quArr = Object.values(this.data.query2[cityArr[0]].qu)
                quArr.unshift("全部")
                data.multiArray[2] = quArr
                data.multiIndex[1] = 0;
                data.multiIndex[2] = 0;
                break;
            case 1:
                quArr = Object.values(this.data.query2[data.multiArray[1][e.detail.value]].qu)
                quArr.unshift("全部")
                data.multiArray[2] = quArr
                data.multiIndex[2] = 0;
                break;
        }

        this.setData(data);
    },
    // 目的地确认时
    async goPickerChange(e) {
        if (this.data.fromCity == this.data.multiArray2[1][this.data.multiIndex2[1]]) {
            ks.showToast({
                title: '请不要选择相同的城市',
                icon: 'none'
            })
            return
        }
        this.setData({
            multiIndex2: e.detail.value,
            // fromCity:this.data.multiArray2[2][this.data.multiIndex2[2]],
            // fromCityCode:'sz',
            // fromQu:'南山区',
            goCity: this.data.multiArray2[1][this.data.multiIndex2[1]],
            goCityCode: await this.getCityCode(this.data.multiArray2[1][this.data.multiIndex2[1]]),
            goQu: this.data.multiArray2[2][this.data.multiIndex2[2]]
        })
        this.getDetailInfoData()

    },
    // 当出发地列发生变化时
    goColumnChange: function (e) {

        var data = {
            multiArray2: this.data.multiArray2,
            multiIndex2: this.data.multiIndex2
        };
        data.multiIndex2[e.detail.column] = e.detail.value;
        switch (e.detail.column) {
            case 0:
                let cityArr = this.data.query1.filter((item) => {
                    return item.province == this.data.multiArray2[0][e.detail.value]
                })[0].citylist.map((item) => {
                    return item.cityname
                }).filter((item) => {
                    return item != "选择城市"
                })
                data.multiArray2[1] = cityArr
                let quArr = Object.values(this.data.query2[cityArr[0]].qu)
                quArr.unshift("全部")
                data.multiArray2[2] = quArr
                data.multiIndex2[1] = 0;
                data.multiIndex2[2] = 0;
                break;
            case 1:

                quArr = Object.values(this.data.query2[data.multiArray2[1][e.detail.value]].qu)
                quArr.unshift("全部")
                data.multiArray2[2] = quArr
                data.multiIndex2[2] = 0;
                break;
        }

        this.setData(data);
    },
    onLoad: function async (options) {
        this.render(options)
    },
    //渲染整个页面
    render(options) {
        util.getUrl(app.globalData.url).then(res => {
            this.getProvinceData(options.city || '');
            const query = ks.createSelectorQuery()
            setTimeout(() => {
                query.select('.change-city').boundingClientRect()
                query.selectViewport().scrollOffset()
                query.exec(res => {
                    if (res[0])
                        this.setData({
                            marginTop: res[0].height
                        })
                })
            }, 200);

        });
    },

    // 获取公告
    getAnnounce(citycode) {
        util.request('zhuanti.php', {
            action: "geli_notice",
            citycode: citycode
        }, "POST").then((e) => {
            this.setData({
                announce: e.data.data.daoyu,
                announceInfo: e.data.data.arr
            })
        })
    },

    // 打开和关闭公告
    openAnnounce() {
        this.setData({
            showAnnounce: true
        })
    },
    closeAnnounce(e) {
        if (e.detail.val == 0) {
            this.setData({
                showAnnounce: false
            })
        }
        if (e.detail.val == 1) {
            this.data.announceInfo.id ? ks.navigateTo({
                url: `/pages/article/detail/detail?id=${this.data.announceInfo.id}&city=${this.data.announceInfo.citycode}&type=${this.data.announceInfo.type}`,
            }) : ks.showToast({
                title: '暂时还没有这个公告详情哦',
                icon: 'none'
            })
        }

    },
    // 提示
    tip() {
        ks.showModal({
            title: '订阅内容',
            content: '1、全国疫情风险等级变更\r\n2、疫情相关政策变更告知\r\n3、城市疫情热点告知\r\n4、隔离核酸规定政策告知'
        })
    },
    // 订阅成功
    subsuccess1() {
        this.setData({
            subscribeText1: "已订阅"
        })
    },
    subsuccess2() {
        this.setData({
            subscribeText2: "已订阅"
        })
    },
    // 检查是否订阅
    check(city, num) {
        util.request("sub_message.php", {
            action: "check",
            name: "疫情信息通知",
            city: city,
            openid: ks.getStorageSync("openid")
        }, "POST").then(res => {
            switch (num) {
                case 1:
                    this.setData({
                        subscribeText1: res.data.state == 0 ? "+订阅城市" : "已订阅"
                    });
                    break;
                case 2:
                    this.setData({
                        subscribeText2: res.data.state == 0 ? "+订阅城市" : "已订阅"
                    });
                    break;
            }
        });
    },

    // 前往工具箱详情
    toTool(e) {
        let path = e.currentTarget.dataset.path;
        let linkname = e.currentTarget.dataset.title;
        let appid = e.currentTarget.dataset.appid || '';
        if (path) {
            if (path.indexOf("pages") == -1 && path.indexOf("mp.weixin.qq.com") == -1 && !appid) {
                this.setData({
                    showtk: true
                })
                util.navContact(linkname, path)
            } else {
                util.navMethod(path, appid);
            }
        } else {
            ks.showToast({
                title: '还没有这个入口哦~',
                icon: 'none'
            })
        }
    },

    getLocation() {
        qqmapsdk.reverseGeocoder({
            success: (res) => {
                let city = res.result.address_component.city;
                let province = res.result.address_component.province;
                let provinceIndex, cityIndex, toProvinceIndex;
                // let city="芜湖市";
                let citydata;
                if (province && city) {
                    let findProvince = this.data.leaveProvPick.filter(pro => province.includes(pro.province))[0];
                    provinceIndex = this.data.leaveProvPick.findIndex(pro => province.includes(pro.province));
                    // toProvinceIndex = this.data.provPick.findIndex(pro => province.includes(pro.province));
                    if (findProvince) {
                        citydata = findProvince.citylist.filter(findCity => city.includes(findCity.cityname))[0];
                        cityIndex = findProvince.citylist.findIndex(findCity => city.includes(findCity.cityname));
                    }
                }
                if (citydata != '' && city.indexOf(this.data.city) == -1) {
                    ks.showModal({
                        content: '您当前定位城市为' + city + '\n是否需要切换到' + city + '隔离政策查询？',
                        success: res => {
                            if (res.confirm) {
                                this.setData({
                                    city: citydata.cityname,
                                    citycode: citydata.citycode,
                                    province,
                                    leavePindex: provinceIndex,
                                    leaveCindex: cityIndex,
                                    // pindex: toProvinceIndex,
                                    cindex: 0,
                                    fromCity: citydata.cityname,
                                    fromCityCode: citydata.citycode
                                });
                                this.getQrcode();
                                this.bindCity({
                                    detail: {
                                        value: this.data.leaveCindex
                                    }
                                });
                            }
                        }
                    })
                }
            },
        });
    },

    getInfoData() {
        util.request('zhuanti.php', {
            action: "geli_all",
            type: "city",
            citycode: this.data.citycode
        }, ).then(res => {
            if (res.data.data.data) {
                res.data.data.data.forEach(item => item.over = false);
                this.info = res.data.data;
                if (res.data.data.hasOwnProperty("daofen") && res.data.data.daofen) {
                    res.data.data.daofen.content = res.data.data.daofen.content
                        .replace(/<p([\s\w"=\/\.:;]+)((?:(="[^"]+")))/ig, '<p')
                        .replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
                        .replace(/<p([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<p')
                        .replace(/<p>/ig, '<p class="p_class">')
                        .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
                        .replace(/<img/gi, '<img style="width:100%;height:auto"')
                }
                this.setData({
                    infoData: res.data.data.data,
                    daofen: res.data.data.daofen,
                });
                this.title = res.data.data.title;
                let data = this.data.infoData.filter(item => item.leavecity == this.data.city).slice(0, 5);
                if (this.data.infoData.length > 5 && data.length >= 5) {
                    this.setData({
                        showMore: true,
                    });
                }

                allInfo = this.data.infoData.filter(item => item.leavecity == this.data.city);
                this.setData({
                    geliInfo: data,
                });
            }
        });

    },

    showMoreInfo() {
        this.setData({
            geliInfo: allInfo,
            showMore: false,
        })
    },
    // 出行政策选择tab
    chooseDiffTab(e) {
        if (this.data.curDiffIndex == e.currentTarget.dataset.index) {
            return
        }
        this.setData({
            curDiffIndex: e.currentTarget.dataset.index,
            curDiffTitle: this.data.differentTitle[e.currentTarget.dataset.index]
        })
    },
    // 查看更多进出政策
    more() {
       ks.navigateTo({
         url: '/pages/topicality/chuxingtraffic/chuxingtraffic',
       })
    },
    // 渲染进出政策
    renderjczhengce(citycode) {
        util.request('zhuanti.php', {
            action: 'jczhengce',
            citycode: citycode
        }).then(e => {
            this.setData({
                differentContent: e.data.data.list || [],
                differentTitle: e.data.data.data || [],
                curDiffTitle: e.data.data.data[0] || 0,
            })
           
        })
    },
    
    // 获取cityCode,参数为市
    async getCityCode(city) {
        const res = await util.request("citycode.php", {
            action: "city",
            city: city
        }, "POST")

        return res.data.data[0].citycode

    },
    // 颠倒出发地和目的地
    reserveLocation() {
        const fromCity = this.data.fromCity
        const fromCityCode = this.data.fromCityCode
        const fromQu = this.data.fromQu
        let data = {
            fromCity: this.data.goCity,
            fromCityCode: this.data.goCityCode,
            fromQu: this.data.goQu,
            goCity: fromCity,
            goCityCode: fromCityCode,
            goQu: fromQu
        }

        const arr = Object.values(data).filter((item) => {
            return item == "请选择"
        })
        if (arr.length == 0) {
            this.setData(
                data
            )
            this.getDetailInfoData()
        } else {
            ks.showToast({
                title: '请选择出发地或目的地',
                icon: 'none'
            })
        }


    },
    // 获取省市区
    getProvinceData(optcode) {
        let data = {
            action: "geli_all_qu",
            type: "city",
            citycode: optcode ? optcode : this.data.citycode,
        };
        util.request('zhuanti.php', data, ).then(res => {
            let query1 = res.data.data.cityname.city
            let query2 = res.data.data.qu
            this.setData({
                query1,
                query2
            })

            let provinceArr = query1.map((item) => {
                return item.province
            })
            let cityArr = query1[0].citylist.map((item) => {
                return item.cityname
            })

            let quArr = Object.values(query2[cityArr[0]].qu)
            quArr.unshift("全部")

            let data = {
                multiArray: this.data.multiArray,
                multiArray2: this.data.multiArray2
            }

            data.multiArray[0] = provinceArr
            data.multiArray[1] = cityArr
            data.multiArray[2] = quArr
            data.multiArray2[0] = provinceArr
            data.multiArray2[1] = cityArr
            data.multiArray2[2] = quArr
            this.setData(
                data
            )
            if (res.data.data) {
                this.qu = res.data.data.qu;
                if (res.data.data.cityname) {
                    res.data.data.cityname.city.unshift({
                        province: "请选择",
                        citylist: []
                    });
                    res.data.data.cityname.city.forEach(citys => {
                        citys.citylist.unshift({
                            cityname: "选择城市"
                        })
                    });
                }

                if (res.data.data.leave && res.data.data.leave.city)
                    res.data.data.leave.city.forEach(citys => {
                        citys.citylist.unshift({
                            cityname: "选择城市"
                        });
                    });
                this.setData({
                    leaveProvPick: this.data.leaveProvPick.length ? this.data.leaveProvPick : res.data.data.leave.city,
                    provPick: this.data.provPick.length ? this.data.provPick : res.data.data.cityname.city,
                    infoData: res.data.data.leavecity,
                });
                this.info = res.data.data;
                let leavePindex = this.data.leaveProvPick.findIndex(item => item.province == this.data.province) ? this.data.leaveProvPick.findIndex(item => item.province == this.data.province) : 0;
                let leaveCindex = this.data.leaveProvPick[leavePindex].citylist.findIndex(item => item.cityname == this.data.city);
                // let toPindex = this.data.provPick.findIndex(item => item.province == this.data.province) ? this.data.provPick.findIndex(item => item.province == this.data.province) : 0;
                this.setData({
                    leavePindex,
                    leaveCindex,
                    // pindex: toPindex,
                });


                if (res.data.data.leave.city && optcode)
                    res.data.data.leave.city.forEach((provinces) => provinces.citylist.forEach(city => {
                        if (city.citycode == optcode)
                            this.setData({
                                leavePindex: this.data.leaveProvPick.findIndex(item => item.province == provinces.province),
                                leaveCindex: this.data.leaveProvPick[this.data.leaveProvPick.findIndex(item => item.province == provinces.province)].citylist.findIndex(item => item.citycode == optcode),
                                city: city.cityname,
                                citycode: city.citycode,
                            });
                    }));

                let data = this.data.infoData.filter(item => item.leavecity == this.data.city).slice(0, 5);
                if (res.data.data.qu[this.data.city]) {
                    let leaveQu = Object.keys(res.data.data.qu[this.data.city].qu);
                    leaveQu.unshift("请选择区县名称");
                    this.setData({
                        leaveQu
                    });
                }
                data.forEach(item => item.over = false);
                if (this.data.infoData.length > 5) {
                    allInfo = this.data.infoData.filter(item => item.leavecity == this.data.city);
                    this.setData({
                        showMore: true,
                    });
                }
                if (res.data.data.hasOwnProperty("daofen") && res.data.data.daofen) {
                    res.data.data.daofen.content = res.data.data.daofen.content
                        .replace(/<p([\s\w"=\/\.:;]+)((?:(="[^"]+")))/ig, '<p')
                        .replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
                        .replace(/<p([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<p')
                        .replace(/<p>/ig, '<p class="p_class">')
                        .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
                        .replace(/<img/gi, '<img style="width:100%;height:auto"')
                    // .replace(/<span>/ig, '<p class="p_class">')
                }
                this.setData({
                    // geliInfo: data,
                    daofen: res.data.data.daofen,
                });
                if (!optcode)
                    this.getLocation();
            } else {
                ks.showToast({
                    title: '当前城市暂无隔离信息',
                    icon: 'none',
                });
            }

            this.getDetailInfoData()
        });
    },

    bindProv(e) {
        this.setData({
            leavePindex: e.detail.value,
            leaveCindex: 0,
            leaveQu: ["请选择区县名称"],
            leaveQuIndex: 0,
        });
    },

    bindToProv(e) {
        this.setData({
            pindex: e.detail.value,
            cindex: 0,
            geliInfo: allInfo.filter(item => item.leavecity == this.data.city).slice(0, 5),
            showMore: true,
            showDetail: false,
            arriveQu: ["请选择区县名称"],
            arriveQuIndex: 0,
        });
    },

    bindCity(e) {
        let cityData;
        this.setData({
            leaveCindex: e.detail.value ? e.detail.value : 0,
            leaveQuIndex: 0,
        });
        if (e.detail.value != 0) {
            this.getDetailInfoData()
            cityData = this.data.leaveProvPick[this.data.leavePindex].citylist[e.detail.value];
            if (cityData) {
                let leaveQu
                if (this.qu[cityData.cityname]) {
                    leaveQu = Object.keys(this.qu[cityData.cityname].qu);
                    leaveQu.unshift("请选择区县名称");
                }
                this.setData({
                    citycode: cityData.citycode,
                    city: cityData.cityname,
                    leaveQu
                });

            }
            if (this.data.cindex != 0)
                this.getDetailInfoData();
            else
                this.getInfoData();
        } else
            this.setData({
                leaveQu: ["请选择区县名称"],
                leaveQuIndex: 0
            });

    },

    // 渲染详情
    getDetailInfoData() {
        let data = {
            action: "geli_all_qu",
            type: "city",
        };
        data.citycode = this.data.fromCityCode //出发地城市code
        data.leavequ = this.data.fromQu == '全部' ? '' : this.data.fromQu //出发地区县
        data.arrive = this.data.goCityCode //目的地城市code
        data.arrivequ = this.data.goQu == '全部' ? '' : this.data.goQu //目的地区县
        this.getAnnounce(data.citycode)
        this.renderjczhengce(data.citycode)
        this.selectComponent("#fangyiTools").getTools(data.cityCode)
        util.request("zhuanti.php", data, "POST").then(res => {
            if (res.data.data) {
                res.data.data.leavecity ? this.check(res.data.data.leavecity[0].leavecity, 1) : ''
                res.data.data.leavecity ? this.check(res.data.data.leavecity[0].cityname, 2) : ''
                this.setData({
                    detailInfo: res.data.data
                });

            }
        })
    },

    leaveQuChange(e) {
        this.setData({
            leaveQuIndex: e.detail.value,
        });
        this.getDetailInfoData();
    },

    arriveQuChange(e) {
        this.setData({
            arriveQuIndex: e.detail.value,
        });
        this.getDetailInfoData();
    },

    // 获取城市公众号二维码
    getQrcode() {
        util.cityConfig(this.data.citycode).then(res => {
            this.setData({
                qrcodeimg: res.qrcode,
            })
        })
    },

    detail(e) {
        let index = e.currentTarget.dataset.index;
        this.data.geliInfo[index].over = !this.data.geliInfo[index].over;
        this.setData({
            [`geliInfo[${index}]`]: this.data.geliInfo[index],
        });
    },

    openDetail(e) {
        let data = this.data.geliInfo[e.currentTarget.dataset.index];
        if (data.arr.id)
            ks.navigateTo({
                url: `/pages/article/detail/detail?id=${data.arr.id}&type=${data.arr.type}&city=${data.arr.citycode ? data.arr.citycode : this.data.citycode}`,
            });
        else {
            this.setData({
                showtk: true
            })
            util.navContact(this.data.detailInfo.title, data.url);
        }

    },
    // 隔离/核酸详情展示
    showCityContentDetail(e) {
        let index = util.getValue("index", e);
        this.data.showMessage[index] = !this.data.showMessage[index];
        this.setData({
            showMessage: this.data.showMessage,
        });
    },
    // 登记/报备规定展示
    showDengjiDetail(e) {
        let index = util.getValue("index", e);
        this.data.showDengji[index] = !this.data.showDengji[index];
        this.setData({
            showDengji: this.data.showDengji,
        });
    },
    // 进入客服会话
    contact() {
        this.setData({
            showtk: false,
        })
    },

    // 关闭
    close() {
        this.setData({
            showtk: false,
        })
    },

    articleDetail(e) {
        let data = util.getValue("key", e);
        if (data) {
            if (data.id)
                ks.navigateTo({
                    url: `/pages/article/detail/detail?id=${data.id}&city=${data.citycode}&type=${data.type}`,
                });
            else {
                this.setData({
                    showtk: true
                })
                util.navContact(this.data.detailInfo.title, data.url);
            }
        }
    },

    onPageScroll: function (e) {
        if (this.data.showNav)
            this.setData({
                showNav: false,
            });
    },

    onShareAppMessage: function () {
        return {
            title: this.info.title ? this.info.title : "隔离政策查询",
        }
    },
    onShareTimeline: function () {
        return {
            title: this.data.data ? this.data.data.title : '隔离政策查询',
            imageUrl: this.data.data ? this.data.data.images : 'http://imgbdb3.bendibao.com/xcxbdb/file/20212/9/20210209161843_68677.jpg',
        }
    },
})